package com.yunmai.web.common.sms;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import com.yunmai.web.config.config.SubMailShortMessageConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 * @author WangChen
 * @since 2021-03-12 09:11
 **/
@Component
public class SmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsService.class);

    private static final String PROJECT = "J0iRS2";

    @Autowired
    public RestTemplate restTemplate;

    @Autowired
    public SubMailShortMessageConfig subMailConfig;


    public boolean send(String phone, String code, int expireMinutes) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code);
        jsonObject.put("time", expireMinutes);
        return send(phone, jsonObject);
    }

    private boolean send(String phone, JSONObject jsonVars) {
        String url = subMailConfig.getUrl();
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("appid", subMailConfig.getAppid());
            jsonObject.put("to", phone);
            jsonObject.put("project", PROJECT);
            jsonObject.put("signature", subMailConfig.getSignature());

            //对所有的数据进行UrlEncode
            JSONObject jsonNew = new JSONObject();
            Iterator<String> iterator = jsonVars.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object val = jsonVars.get(key);
                if (val instanceof String) {
                    String valNew = URLEncoder.encode(val.toString(), "UTF-8");
                    jsonNew.put(key, valNew);
                } else {
                    jsonNew.put(key, val);
                }
            }
            jsonObject.put("vars", jsonNew);

            String reqJsonStr = jsonObject.toString();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<String>(reqJsonStr, headers);
            ResponseEntity<Map> resp = restTemplate.exchange(url, HttpMethod.POST, entity, Map.class);

            String status = (String) resp.getBody().get("status");
            if (status != null && status.equals("success")) {
                return true;
            }
            return false;
        } catch (Exception ex) {
            logger.info("[SmsService] send error = {}", ExceptionUtil.stacktraceToString(ex));
            return false;
        }
    }


}
